import java.io.InputStream;

import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

public class Schedule {

	public static final String CONFIG_FILE = "/trigger.properties";
	public static final java.util.Properties appConfig = new java.util.Properties();

	public Schedule() throws Exception {

		// Load the properties value from file
		try {
			InputStream stream = this.getClass().getResourceAsStream(
					CONFIG_FILE);
			if (stream != null) {
				appConfig.load(stream);
			} else {
				throw new Exception("Input Stream is null");
			}
		} catch (Exception e) {
			System.err.println("Error loading file " + CONFIG_FILE);
			System.err.println(e.getMessage());
			e.printStackTrace();
			throw new Exception(e);
		}

	}

	public static void main(String args[]) throws Exception {
		Schedule schedule = new Schedule();
		try {
			for (int i = 1; i <= Integer.parseInt(appConfig.getProperty("batch.number")); i++) {
				if (appConfig.getProperty("batch.cron.trigger" + i).length() != 0) {

					String batchcron = appConfig
							.getProperty("batch.cron.trigger" + i);
					String pathfile = appConfig.getProperty("batch.path.file"
							+ i);

					schedule.executeBatch(batchcron, pathfile);
				} else {
					System.out.println("no setting found");
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public void executeBatch(String cronTrigger, String path) throws Exception {
		JobDataMap datamap = new JobDataMap();
		datamap.put("path", path);

		JobDetail job = new JobDetail();
		job.setJobClass(ExecuteBatch.class);
		job.setName("executeBatch" + path);
		job.setJobDataMap(datamap);

		CronTrigger trigger = new CronTrigger();
		trigger.setCronExpression(cronTrigger);
		trigger.setName("executeBatch" + path);

		Scheduler scheduler = new StdSchedulerFactory().getScheduler();
		scheduler.scheduleJob(job, trigger);
		scheduler.start();

	}

}
